/**
 * @title 高级表格的基础应用(基本示例1)
 * @description 多选、合计、分页、列拖拽、列过滤
 *
 */
import React, { Component } from "react";

import Modal from 'bee-modal';
import 'bee-modal/build/Modal.css';

import { Button, Icon, Tree,  Checkbox} from "tinper-bee";

import Table from "bee-table";
import 'bee-table/build/Table.css';

import { vendorsSetStorage, vendorsGetStorage, vendorsDanger, vendorsFmtDate, vendorsGetUrlParam } from 'utils/config.js';
import axios from 'axios';
import './index.less'

const TreeNode = Tree.TreeNode;

class ReferSingleSelect extends Component {
    constructor(props) {
        super(props);
        let _self = this;
        this.state = {
            item: {},
            columns: [],
            selectedList: [],
            showModal: false,
            data: [],
        }
    }

    close = () => {
        this.setState({
            showModal: false
        }, () => {
            // let { item: { refPk }, data, selectedList } = this.state;
            // let showValue = this.getShowValue()
            // this.props.upDataValues(refPk, showValue)
        })
    }

    showGrid = ({ item, index, dataSource, reqData }) => {
        let { reqRef, refPk } = item;
        // let newcolumns = this.setColumns(item)
        let cacheData = vendorsGetStorage(dataSource)

        if (cacheData && cacheData[refPk] && cacheData[refPk]['refData'].length && (
            (typeof cacheData[refPk]['reqData'] === 'string' && cacheData[refPk]['reqData'] == reqData) ||
            JSON.stringify(cacheData[refPk]['reqData']) === JSON.stringify(reqData)
        )) {

            this.setState({
                showModal: true,
                dataSource,
                item,
                data: cacheData[item.refPk]['refData'],
                selectedList: cacheData[item.refPk]['selectedList'],
            })
            return

        }
        this.updataRefData({ item, index, dataSource, reqData })
    }

    updataRefData = ({ item, index, dataSource, reqData }) => {
        let { reqRef } = item;
        this.setState({
            showModal: true,
            dataSource,
            item,
            data: [],
            selectedList: [],
            // columns: newcolumns
        }, () => {
            // this.setState({
            //     data: [{pkOrg:"00013A10000000005HIH", orgName: '固定组织', orgCode: "yyq"}],
            // }, () => {
            //     let { data, selectedList } = this.state;
            //     this.updataRefcache({ data, selectedList, reqData });
            // })
            let dataKey = reqRef.method === "get" ? "params" : 'data'
            axios({
                method: reqRef.method,
                url: reqRef.refUrl,
                [dataKey]: reqData,
                headers: {
                    'Cache-Control': 'no-cache',
                }
            }).then((res) => {
                let data = res.data;
                if (data.resultCode === 'ok') {
                    // data = {"resultCode":"ok","result":{"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":null,"pkSrc":null,"pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":"botawq9w","scode":"jdxizpgcrzei3wgf","sname":"工程云测试V2.7","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":[{"changeFlag":"22c278b8-554b-418d-8612-afd7a9736309","dr":0,"assignInfo":null,"pkOrganization":"13393469-8792-4ca2-8bbe-732d5b38c66f","pkSrc":"0001D310000000002UN3","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"2021","sname":"幸福集团","innerCode":null,"isLastVersion":null,"enableState":2,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null}],"isDistributed":null,"tenantName":"工程云测试V2.7","tenantCode":"jdxizpgcrzei3wgf"}}
                    this.setState({
                        data: [data.result],
                    }, () => {
                        let { data, selectedList, item: { refPk }} = this.state;
                        let showValue = this.getShowValue()
                        this.props.upDataValues(refPk, showValue)
                        this.updataRefcache({ data, selectedList, reqData });
                    })
                } else {
                    vendorsDanger({ 'text': data.exMsg })
                }
            })
        })
    }
    getSelectedDataFunc = (selectedList, record, index, newData) => {

    };

    updataRefcache = ({ data, selectedList, reqData }) => {
        let { dataSource, item: { refPk, selectShowKey } } = this.state;
        let cacheData = vendorsGetStorage(dataSource)
        console.log(cacheData)
        if (!cacheData[refPk]) {
            cacheData[refPk] = {}
        }
        cacheData[refPk]['refData'] = data
        cacheData[refPk]['selectedList'] = selectedList
        if (reqData) {
            cacheData[refPk]['reqData'] = reqData
        }
        vendorsSetStorage(dataSource, cacheData)
    }

    getShowValue = () => {
        let { selectedList, item: { refPk, selectShowKey } } = this.state;
        let value = ''
        selectedList.map((item, index) => {
            if (selectedList.length - 1 === index) {
                value += `${item[selectShowKey]}`
            } else {
                value += `${item[selectShowKey]},`
            }
        })
        return value
    }


    sureClick = () => {
        let { item: { refPk }, data, selectedList } = this.state;
        this.updataRefcache({ data, selectedList });
        let showValue = this.getShowValue()
        this.setState({
            showModal: false,
        }, () => {
            this.props.upDataValues(refPk, showValue)
        })
    }
    addChecked = (e, pk, data) => {
        for (let i = 0; i < data.length; i++) {
            let dataItem = data[i];
            let dataItemPk = dataItem.pkOrganization ? dataItem.pkOrganization : dataItem.pkTenant;
            dataItem['_checked'] = false
            if (pk == dataItemPk) {
                dataItem['_checked'] = e
            }
            if (dataItem.children && dataItem.children.length) {
                this.addChecked(e, pk, dataItem.children)
            }
        }
    }
    changeData = (e, item) => {
        let pk = item.pkOrganization ? item.pkOrganization : item.pkTenant;
        let data = this.state.data;
        this.addChecked(e, pk, data)
        return data
    }
    onCheckBoxChange = (_checked, item) => {
        let data = this.changeData(!_checked, item)
        let selectedList = []
        if (!_checked) {
            selectedList = [{ ...item, _checked: !_checked }]
        }

        this.setState({
            data,
            selectedList
        }, () => {
                console.log(data) 
                console.log(2) 
        })
    }
    loop = data => data.map((item) => {
        console.log(item)
        let _checked = item._checked? item._checked : false
        if (item.sname) {
            let title = <div className="rowItem" key={item.pkOrganization} onClick={(e) => {
                this.onCheckBoxChange(_checked, item)
            }}>
                <Checkbox
                    className="checkbox"
                    checked={_checked}
                />
                <div>{item.sname}</div>
            </div>

            if (item.children && item.children.length) {
                return <TreeNode key={item.pkOrganization} title={title}>{this.loop(item.children)}</TreeNode>;
            }
            return <TreeNode key={item.pkOrganization} title={title} />;
        }
    })
    
    render() {

        return (
            <div>
                <Modal show={this.state.showModal} size={'lg'} onHide={this.close} backdrop={false}>
                    <Modal.Header closeButton>
                        <Modal.Title > {this.state.item.label} </Modal.Title>
                    </Modal.Header >
                    <Modal.Body>

                        <Tree>
                            {this.loop(this.state.data)}
                        </Tree>

                    </Modal.Body>
                    <Modal.Footer>
                        <div className="refer-btn-group">
                            <Button className='icon-cancel-btn' onClick={this.close}> 取消 </Button>
                            <Button colors="primary" onClick={this.sureClick}> 确认 </Button>
                        </div>
                    </Modal.Footer>
                </Modal>
            </div >
        );
    }
}
export default ReferSingleSelect;